package com.seng.resourcetycoon.gui.views;

import com.seng.resourcetycoon.HelloApplication;
import com.seng.resourcetycoon.gui.models.LoadBearer;
import com.seng.resourcetycoon.util.ResourceReader;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;

import java.io.*;
import java.util.Objects;

public class LoadBearerItemView {
    double endx = 700;
    private LoadBearer loadBearer;

    @FXML
    private VBox content;
    @FXML
    private Label requirement;
    @FXML
    private Label loaded;
    @FXML
    private ImageView image;
    private  boolean stop;
    private double initialCarPositionX = 0;

    double speed = 10; // 设置小车的速度

    public boolean refreshPosition(){
        if(stop){
            return false;
        }
        // 计算新的位置
        double newX = initialCarPositionX + speed * 0.01;

        // 更新小车位置
        content.setTranslateX(newX);
        initialCarPositionX = newX;

        // 如果达到目标位置，停止动画
        if (newX >= endx) {
            stop = true;
            ((Pane)content.getParent()).getChildren().remove(content);
        }

        return true;
    }

    public boolean refreshRequirementByCart(LoadBearer loadBearer){
        if(Objects.equals(this.loadBearer, loadBearer)){
            refreshRequirementCapacities();
            return true;
        }
        return false;
    }

    public LoadBearerItemView(){
        FXMLLoader fxmlLoader = new FXMLLoader(HelloApplication.class.getResource("cart-view.fxml"));
        fxmlLoader.setController(this);
        try {
            fxmlLoader.load();
        }catch (IOException e){
            throw new RuntimeException(e);
        }
    }

    public void bindData(LoadBearer loadBearer) {
        this.loadBearer = loadBearer;
        requirement.setText(loadBearer.reportRequirementCapacities());
        loaded.setText(loadBearer.reportLoadedCapacities());
        try{
            Image image1 = new Image(ResourceReader.getResourceAsStream("cart.png"));
            image.setImage(image1);
        }catch (Exception e){
            e.printStackTrace();
        }


    }

    public VBox getContent() {
        return content;
    }


    public void refreshLoadedCapacities() {
        loaded.setText(loadBearer.reportLoadedCapacities());
    }

    public void refreshRequirementCapacities(){
        requirement.setText(loadBearer.reportRequirementCapacities());
    }
}
